package com.quasar.quasar.ctrl;

import co.paralleluniverse.fibers.Fiber;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;

/**
 * @time:2020/6/30
 * @author:tan
 * @function:
 */
@RestController
@RequestMapping(path = "/fiber")
public class FiberRestCtrl {

    @GetMapping("/get")
    public String getFiber(){
        new Fiber<>(() -> {
            try {
                sendHttp();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            System.out.println("fiber sleep done");
        }).start();
        return "ok";
    }

     void sendHttp() throws MalformedURLException {
        URL url = new URL("https://ssp.gdsinsing.com/assets/js/login.js");
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            try (InputStream inputStream = httpURLConnection.getInputStream()){
                ByteBuffer buffer = ByteBuffer.allocate( inputStream.available() );
                inputStream.read( buffer.array() );
                System.out.println(String.format("thread: %s content: %s", Thread.currentThread().getName(), new String(buffer.array())));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null){
                httpURLConnection.disconnect();
            }
        }
    }
}
